/**
 * Malsha 21/07/2014
 */

UserGroup = new Object();

var user_groupId = null;

var user_group_store = Ext.create('Ext.data.Store', {
	fields : [ 'id', 'groupCode', 'groupName', 'isfundManager' ]
});

UserGroup.getTreePanel = function() {

	var store = Ext.create('Ext.data.TreeStore', {
		fields : [ 'id', 'text', 'leaf', 'expanded', 'checked', 'childMenuItems', 'result', 'create', 'confirm', 'reject', 'view', 'screenId', 'parentId' ],
		autoLoad : true,
		root : {
			text : 'Main Menu',
			id : 0,
			screenId : 0,
			expanded : true
		},
		proxy : {
			type : 'ajax',
			url : 'getAllMenus.action',
			reader : {
				type : 'json',
				root : 'result'
			}
		}
	});

	var menuTree = Ext.create('Ext.tree.Panel', {
		title : 'Screen',
		useArrows : true,
		lines : false,
		width : 250,
		height : 400,
		id : 'tree',
		rootVisible : false,
		store : store,
		plugins : [ Ext.create('Ext.grid.plugin.CellEditing', {
			clicksToEdit : 1
		}) ],
		columns : {
			items : [ {
				xtype : 'treecolumn',
				text : 'Menu',
				flex : 2,
				sortable : true,
				dataIndex : 'text'
			}, {
				xtype : 'mytreecheckcolumn',
				header : 'View',
				dataIndex : 'view',
				align : 'center',
				stopSelection : false,
			}, {
				xtype : 'mytreecheckcolumn',
				header : 'Save',
				dataIndex : 'create',
				align : 'center',
				stopSelection : false
			}, {
				xtype : 'mytreecheckcolumn',
				header : 'Confirm',
				dataIndex : 'confirm',
				align : 'center',
				stopSelection : false,
			}, {
				xtype : 'mytreecheckcolumn',
				header : 'Reject',
				dataIndex : 'reject',
				align : 'center',
				stopSelection : false
			} ],
			defaults : {
				flex : 1
			}
		},
		listeners : {
			checkchange : function(node, checked, eOpts) {
				if (node.isLeaf()) {
					if (!UserGroup.getCheckedNextSibling(node) && !UserGroup.getCheckedPreviousSibling(node))
						UserGroup.selectParentNodes(node, checked);
				}
			}
		}
	});
	function renderInstall(value, id, r) {
		var id = Ext.id();
		if (r.data.leaf == true) {
			if (value != 0) {
				Ext.defer(function() {
					if (Ext.get(id)) {

					}
				}, 50);
				return Ext.String.format('<div id="{0}"></div>', id);
			} else {
				return;
			}
		} else {
			return;
		}
	}
	return menuTree;

};

UserGroup.getCheckedNextSibling = function(node) {

	var nextsibling = node.nextSibling;
	var checkedsiblings = false;
	if (nextsibling) {
		if (nextsibling.get('checked') == true) {
			checkedsiblings = true;
			return checkedsiblings;
		} else {
			checkedsiblings = UserGroup.getCheckedNextSibling(nextsibling);
		}
	}
	return checkedsiblings;
};

UserGroup.getCheckedPreviousSibling = function(node) {

	var previoussibling = node.previousSibling;
	var checkedsiblings = false;
	if (previoussibling) {
		if (previoussibling.get('checked') == true) {
			checkedsiblings = true;
			return checkedsiblings;
		} else {
			checkedsiblings = UserGroup.getCheckedPreviousSibling(previoussibling);
		}
	}
	return checkedsiblings;
};

UserGroup.selectParentNodes = function(node, checked) {
	var parentNode = node.parentNode;
	if (parentNode) {
		parentNode.set('checked', checked);
		UserGroup.selectParentNodes(parentNode, checked);
	}
};

UserGroup.getFields = function() {

	var treepanel = UserGroup.getTreePanel();

	return Ext.create('Ext.form.FieldSet', {
		title : 'User Group Details',
		defaults : {
			anchor : '100%',
			msgTarget : 'under',
		},
		items : [ {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'textfield',
				fieldLabel : 'Group Name',
				flex : 1,
				msgTarget : 'under',
				labelWidth : 80,
				padding : '0 5 0 0',
				maxLength : 50,
				allowBlank : false,
				name : 'groupName'
			}, {
				xtype : 'textfield',
				fieldLabel : 'Code',
				flex : 1,
				msgTarget : 'under',
				allowBlank : false,
				name : 'groupCode',
				labelWidth : 45,
				maxLength : 20,
				padding : '0 5 0 0'
			} ]
		}, {
			xtype : 'checkbox',
			boxLabel : 'Is Fund Manager Group',
			name : 'isfundManager',
			inputValue : '1',
		}, treepanel ]
	});
};

UserGroup.getCenterPanel = function() {
	Ext.Loader.setPath('Ext.ux', 'js/libs');

	Ext.Loader.setConfig({
		enabled : true
	});

	Ext.require([ 'Ext.ux.CheckColumn' ]);

	Ext.define('My.tree.column.CheckColumn', {
		extend : 'Ext.ux.CheckColumn',
		alias : 'widget.mytreecheckcolumn',

		processEvent : function(type, view, cell, recordIndex, cellIndex, e, record, row) {
			if (cellIndex == 1) {
				if (record.isLeaf() && record.data.view != null) {
					return this.callParent(arguments);
				} else {
					return My.tree.column.CheckColumn.superclass.superclass.processEvent.apply(this, arguments);
				}
			} else if (cellIndex == 2) {
				if (record.isLeaf() && record.data.create != null) {
					return this.callParent(arguments);
				} else {
					return My.tree.column.CheckColumn.superclass.superclass.processEvent.apply(this, arguments);
				}
			} else if (cellIndex == 3) {
				if (record.isLeaf() && record.data.confirm != null) {
					return this.callParent(arguments);
				} else {
					return My.tree.column.CheckColumn.superclass.superclass.processEvent.apply(this, arguments);
				}
			} else if (cellIndex == 4) {
				if (record.isLeaf() && record.data.reject != null) {
					return this.callParent(arguments);
				} else {
					return My.tree.column.CheckColumn.superclass.superclass.processEvent.apply(this, arguments);
				}
			}

		},

		renderer : function(value, meta, record) {
			if (record.isLeaf() && value != null) {
				return this.callParent(arguments);
			}
			return '';
		}
	});

	var formpanel;
	formpanel = Ext.create('Ext.form.Panel', {
		title : 'User Group',
		bodyPadding : 20,
		autoScroll : true,
		frame : true,
		id : 'user_group_form',
		defaults : {
			labelWidth : 110,
			anchor : '65%',
		},
		items : [ {

			xtype : 'fieldcontainer',
			items : [ {
				xtype : 'triggerfield',
				width : 300,
				triggerCls : 'x-form-search-trigger',
				emptyText : 'Search User Group',
				style : 'float:right;',
				listeners : {
					specialkey : function(field, e) {
						if (e.getKey() == e.ENTER) {
							Ext.Msg.alert('HI', 'Press Enter');
						}
					}
				},
				onTriggerClick : function() {
					var window;
					Ext.Ajax.request({
						url : 'getUserGroup.action',
						success : function(response) {
							var obj = Ext.decode(response.responseText);
							user_group_store.loadRawData(obj.groupDtos);
						}
					});
					if (!window) {
						window = Ext.create('Ext.window.Window', {
							title : 'User Group',
							height : 330,
							frame : true,
							width : 500,
							modal : true,
							constrain : true,
							resizable : false,
							layout : {
								type : 'fit'
							},
							items : [ {
								xtype : 'gridpanel',
								defaults : {
									anchor : '100%'
								},
								store : user_group_store,
								columns : [ {
									text : 'Code',
									dataIndex : 'groupCode',
									flex : 1
								}, {
									text : 'User Group Name',
									dataIndex : 'groupName',
									flex : 1
								} ],
								listeners : {
									itemdblclick : function(dv, record, item, index, e) {
										var data = record.data;
										UserGroup.setFieldData(data, record);
										window.hide();
									}
								}
							} ]
						});
					}
					if (window.isVisible()) {
						window.hide();
					} else {
						window.show();
					}
				}
			} ]
		}, UserGroup.getFields() ],
		buttonAlign : 'center',
		buttons : [ {
			text : 'Cancel',
			handler : function() {
				App.Core.removeScreen();
			}
		}, {
			text : 'Reset',
			handler : function() {
				this.up('form').getForm().reset();
				Ext.getCmp('tree').getStore().load();
				user_groupId = null;
				Ext.getCmp('save').setText('Save');
			}
		}, {
			text : 'Save',
			id : 'save',
			handler : function() {
				var form = this.up('form').getForm();
				var records = getDeepAllChildNodes(Ext.getCmp('tree').getRootNode());
				var screens = [];
				var confirm;
				var create;
				var view;
				var reject;
				for (var i = 0; i < records.length; i++) {
					if (records[i].get('checked')) {
						if (records[i].get('confirm'))
							confirm = true;
						else
							confirm = false;
						if (records[i].get('reject'))
							reject = true;
						else
							reject = false;
						if (records[i].get('create'))
							create = true;
						else
							create = false;
						if (records[i].get('view'))
							view = true;
						else
							view = true;
						var obj = {
							"screenId" : records[i].get('screenId'),
							"menuid" : records[i].get('id'),
							"create" : create,
							"confirm" : confirm,
							"reject" : reject,
							"view" : view,
						};
						screens.push(obj);
					}
				}

				if (form.isValid()) {
					if (user_groupId == null) {
						form.url = 'addUserGroup.action';
						form.submit({
							params : {
								"screenids" : Ext.encode(screens)
							},
							success : function(form, action) {
								form.reset();
								user_groupId = null;
								Ext.getCmp('tree').getStore().load();
								Ext.Msg.alert('Success', 'Saved Successfully');
							},
							failure : function(form, action) {
								Ext.Msg.alert('Failed', action.result.resultMsg);
							}
						});
					} else {
						console.log(user_groupId);
						form.url = 'updateUserGroup.action';
						form.submit({
							params : {
								"screenids" : Ext.encode(screens),
								"x" : user_groupId
							},
							success : function(form, action) {
								form.reset();
								user_groupId = null;
								Ext.getCmp('tree').getStore().load();
								Ext.Msg.alert('Success', 'Saved Successfully');
							},
							failure : function(form, action) {
								Ext.Msg.alert('Failed', action.result.resultMsg);
							}
						});
					}

				}
			}
		} ]
	});
	return formpanel;
};

getDeepAllChildNodes = function(node) {
	var allNodes = new Array();
	if (!Ext.value(node, false)) {
		return [];
	}

	if (!node.hasChildNodes()) {
		return node;
	} else {
		allNodes.push(node);
		node.eachChild(function(Mynode) {
			allNodes = allNodes.concat(getDeepAllChildNodes(Mynode));
		});
	}
	return allNodes;
};

UserGroup.setFieldData = function(data, record) {

	var formPanl = Ext.getCmp('user_group_form');
	// formPanel.setLoading('Loading..', formPanl.getForm());
	user_groupId = data.id;

	Ext.getCmp('save').setText('Update');
	// Ext.getCmp('tree').getStore().load();
	var allChildNodes = getDeepAllChildNodes(Ext.getCmp('tree').getRootNode());
	var myMask = new Ext.LoadMask(formPanl, {
		msg : "Loading..."
	});
	myMask.show();
	Ext.Ajax.request({
		url : 'getSreenbyGroup.action',
		params : {
			"groupid" : user_groupId
		},
		success : function(response) {
			var obj = Ext.decode(response.responseText);

			for (var i = 0; i < allChildNodes.length; i++) {
				allChildNodes[i].set('checked', false);
				if (allChildNodes[i].get('confirm') != null)
					allChildNodes[i].set('confirm', false);
				if (allChildNodes[i].get('create') != null)
					allChildNodes[i].set('create', false);
				if (allChildNodes[i].get('reject') != null)
					allChildNodes[i].set('reject', false);
				if (allChildNodes[i].get('view') != null)
					allChildNodes[i].set('view', false);
				UserGroup.selectParentNodes(allChildNodes[i], false);
				allChildNodes[i].commit();
			}

			for (var i = 0; i < allChildNodes.length; i++) {
				for (var j = 0; j < obj.dtos.length; j++) {

					if (allChildNodes[i].raw.id == obj.dtos[j].menuId) {
						allChildNodes[i].set('checked', true);
						if (allChildNodes[i].get('confirm') != null)
							allChildNodes[i].set('confirm', obj.dtos[j].confirm);
						if (allChildNodes[i].get('create') != null)
							allChildNodes[i].set('create', obj.dtos[j].submit);
						if (allChildNodes[i].get('reject') != null)
							allChildNodes[i].set('reject', obj.dtos[j].reject);
						if (allChildNodes[i].get('view') != null)
							allChildNodes[i].set('view', obj.dtos[j].view);
						UserGroup.selectParentNodes(allChildNodes[i], true);
						allChildNodes[i].commit();
					}
				}
			}
			myMask.hide();
		},
		failure : function(form, action) {
			Ext.Msg.alert('Failed', "No Result");
			myMask.hide();
		}
	});

	formPanl.getForm().loadRecord(record);

};
